<!--
  Copyright 2019 Hackware SpA <human@hackware.cl>
  This file is part of "Hackware Userland" and licensed under the terms
  of the GNU Affero General Public License version 3, or (at your option)
  a later version. You should have received a copy of this license along
  with the software. If not, see <https://www.gnu.org/licenses/>.
-->

<template>
  <div class="wallet-overview">
    <div class="d-flex justify-content-between">
      <h3>
        <small>Saldo total</small> {{ wallet.balance | currency }}
      </h3>
      <router-link
        class="btn btn-primary"
        to="/transactions"
      >
        Ver detalle
        <i class="fas fa-history" />
      </router-link>
    </div>
    <template v-if="dueTransactions.length">
      <hr>
      <h5>Pagos pendientes</h5>
      <table class="table table-sm">
        <thead>
          <tr>
            <th>emisión</th>
            <th>vencimiento</th>
            <th>monto</th>
          </tr>
        </thead>
        <tbody
          v-for="dueTransaction in dueTransactions"
          :key="dueTransaction.id"
        >
          <tr>
            <td>{{ dueTransaction.created_at | date }}</td>
            <td>{{ dueTransaction.due_at | datetime }}</td>
            <td>{{ dueTransaction.amount | currency }}</td>
          </tr>
        </tbody>
      </table>
    </template>
  </div>
</template>

<script>
export default {
  name: 'WalletOverview',
  data() {
    return {
      dueTransactions: [],
      wallet: { balance: 0 },
    };
  },
  created() {
    this.refreshWallet();
    this.$eventHub.$on('payment-updated', this.refreshWallet);
  },
  beforeDestroy() {
    this.$eventHub.$off('payment-updated', this.refreshWallet);
  },
  methods: {
    fetchWallet() {
      this.$fetcher.haweseGet(`/wallets/${this.$auth.uid}`)
        .then((body) => { if (!('error' in body)) { this.wallet = body; } });
    },
    fetchDueTransactions() {
      this.$fetcher.haweseGet('/transactions', { user_uid: this.$auth.uid, due: true })
        .then((body) => { this.dueTransactions = body.data; });
    },
    refreshWallet() {
      this.fetchWallet();
      this.fetchDueTransactions();
    },
  },
};
</script>
